/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.ui.demo;

import com.google.code.mochaccino.framework.ui.i18n.LocaleUtil;
import java.util.Locale;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/** Subject related utilities */
public final class SubjectUtil {
	private static final String KEY_LOCALE = "locale";

	/** Get the Locale */
	public static final Locale getLocale() {
		Subject subject = SecurityUtils.getSubject();
		if ( subject == null ) {
			return LocaleUtil.getDefaultLocale();
		}

		Session session = subject.getSession( false );
		if ( session == null ) {
			return LocaleUtil.getDefaultLocale();
		}

		Locale loc = (Locale) session.getAttribute( KEY_LOCALE );
		if ( loc == null ) {
			return LocaleUtil.getDefaultLocale();
		}

		return loc;
	}

	/** Set the Locale */
	public static final Locale setLocale( String locale ) {
		if ( locale == null ) {
			return getLocale();
		}

		Subject subject = SecurityUtils.getSubject();
		if ( subject == null ) {
			return getLocale();
		}

		Session session = subject.getSession( false );
		if ( session == null ) {
			return getLocale();
		}

		Locale loc = LocaleUtils.toLocale( locale );
		if ( loc == null ) {
			return getLocale();
		}

		session.setAttribute( KEY_LOCALE, loc );
		return loc;
	}
}
